
let baseUrl = '',
    defaultUrl = ''
    urls={},
    fieldMap={},
    items=[],
    nodeValue={},
    nodeMap={},
    index=0,
    nodesLegend=[],
    addItems=[],
    addValue={},
    canAddNode=false,
    nodeTypeList=[],
    relationList=[],
    parentNode={},
    updateItems=[],
    updateValue = {},
    typeMap={},
    needCountryType = 127;

const colorList =  ['166,196,208', '153,204,255', '60,180,75', '255,225,25', '67,99,216', '245,130,49', '145,30,180', '66,212,244', '240,50,230', '191,239,69', '250,190,212', '70,153,144', '220,190,255', '180,210,237', '255,250,200', '128,0,0', '170,255,195', '245,216,200', '199,201,224', '0,0,117', '169,169,169', '255,100,255', '0,0,0', '217,188,214', '153,0,51', '255,102,255', '102,0,153', '153,204,255', '0,51,255', '0,153,255', '0,153,204', '255,255,204', '255,204,102', '204,102,0', '255,153,51', '153,51,0', '153,255,255', '153,255,204', '153,204,153', '102,204,51', '51,153,0', '153,153,0', '204,204,0', '153,153,102', '0,51,0']
const staticNodeMap={
  100:['海军装备','空军装备','陆军装备','航天侦查装备'],
  122:['导弹','鱼雷','声呐','水雷','雷达','特种武器'],//单体装备
  111:'海域',//海域
  115:'港口',//港口
  116:'人员',//人员
  119:'组织机构',//组织机构
  129:['美国海军QT部队','俄罗斯QT部队','中国QT部队','英国QT部队','法国QT部队','日本QT部队','韩国QT部队','印度QT部队']//舰队
}
const nodeList = {
  "海军装备":{
    type:'海军装备',
    field: "name",
    // color: "#004080"
    color: '0,64,128'
  },
  '空军装备':{
    type:'空军装备',
    field: "name",
    // color: "#081fae"
    color: '8,31,174'
  },
  '陆军装备':{
    type:'陆军装备',
    field: "name",
    // color: "#087226"
    color: '8,114,38'
  },
  '航天侦查装备':{
    type:'航天侦查装备',
    field: "name",
    // color: "#0875ae"
    color: '8,117,174'
  },
  '导弹':{
    type:'导弹',
    field: "name",
    // color: "#39a5a4"
    color: '57,165,164'
  },
  '鱼雷':{
    type:'鱼雷',
    field: "name",
    // color: "#066c67"
    color: "6,108,103",
  },
  '声呐':{
    type:'声呐',
    field: "name",
    color: "244,234,42"
    // color: "#f4ea2a"
  },
  '水雷':{
    type:'水雷',
    field: "name",
    // color: "#6308c1"
    color: "99,8,193"
  },
  '雷达':{
    type:'雷达',
    field: "name",
    // color: "#52c108"
    color: "82,193,8"
  },
  '特种武器':{
    type:'特种武器',
    field: "name",
    color: "216,75,64"
    // color: "#d84b40"
  },
  '军事行动':{
    type:'军事行动',
    field: "name",
    color: "26,250,41"
    // color: "#1afa29"
  },
  '海域':{
    type:'海域',
    field: "name",
    color: "0,18,255"
    // color: "#0012ff"
  },
  '港口':{
    type:'港口',
    field: "name",
    color: "129,170,218"
    // color: "#81aada"
  },
  '人员':{
    type:'人员',
    field: "name",
    color: "9,232,214"
    // color: "#09e8d6"
  },
  '服役事故':{
    type:'服役事故',
    field: "name",
    color: "255,0,0"
    // color: "#ff0000"
  },
  '组织机构':{
    type:'组织机构',
    field: "name",
    color: "155,69,148"
    // color: "#9b4594"
  },
  '美国海军QT部队':{
    type:'美国海军QT部队',
    field: "name",
    color: "5,141,252"
    // color: "#058dfc"
  },
  '俄罗斯QT部队':{
    type:'俄罗斯QT部队',
    field: "name",
    color: "234,149,24"
    // color: "#ea9518"
  },
  '中国QT部队':{
    type:'中国QT部队',
    field: "name",
    color: "216,30,6"
    // color: "#d81e06"
  },
  '英国QT部队':{
    type:'英国QT部队',
    field: "name",
    color: "219,99,155"
    // color: "#db639b"
  },
  '法国QT部队':{
    type:'法国QT部队',
    field: "name",
    color: "131,198,194"
    // color: "#83c6c2"
  },
  '日本QT部队':{
    type:'日本QT部队',
    field: "name",
    color: "98,174,6"
    // color: "#62ae06"
  },
  '韩国QT部队':{
    type:'韩国QT部队',
    field: "name",
    color: "219,208,45"
    // color: "#dbd02d"
  },
  '印度QT部队':{
    type:'印度QT部队',
    field: "name",
    color: "14,147,46"
    // color: "#0e932e"
  }
}
window.addEventListener('message',function(e){
  let data = e.data
  baseUrl = data.baseUrl
  defaultUrl = data.defaultUrl
  geturls()
  getImageData()
},false)
// 下钻的接口
// module.exports = {
  function geturls(){
    urls = {
      fetchChildNodeUrl : baseUrl + "/general/getNextNodes",
      delNodeUrl: baseUrl + "/general/delete",
      updateNodeUrl: baseUrl + "/general/updateLabel",
      addNodeUrl: baseUrl + "/general/insertLabel",
      searchUrl: baseUrl + "/weaponry/findByName",
      typeUrl: baseUrl + "/general/getTypeAndNameCH",
      getRelationUrl: baseUrl + "/general/getRelationById",
      addRelationUrl: baseUrl + "/general/userAddRelation",
      //  获取子节点类型
      getChildUrl: baseUrl + "/general/findRelationsByNameAndRelation",
      //  获取节点详情
      getDetailUrl: baseUrl + "/table/",
      // 新增传输字段数据
      getFieldUrl: baseUrl + "/general/getFieldByLabel",
      // 查看节点字段中文名
      getFieldZN: baseUrl + "/general/getFieldById",
      // 查表头
      getHeaderUrl: baseUrl + "/table/",
      // 删除节点关系
      delRelationUrl: baseUrl + "/general/deleteByRelationId",
      //  修改连线的名称
      updateRelationUrl: baseUrl + "/general/userAddRelation",
      // 读取文本的接口，在获取详情的时候调用
      readTxtUrl: baseUrl + "/graph/readingTxt",
      eventUrl: baseUrl + "/weapon/selectEvent/",
      qualityUrl: baseUrl + "/marine/getPercentage",
      relationReasoning: baseUrl + "/general/relationalReasoning",
      getSubmarineCountryUrl: baseUrl + "/general/selectCountryByClass",  //依据潜艇型号查看国家
      getNodeTreeInitUrl: baseUrl + "/navigationTree/getTreeInit",
      getNextnodeTreeUrl: baseUrl + "/navigationTree/getNextNode"
    }
  }
  // 高级检索的接口
  function searchNode(name){
    let result;
    $.ajax({
      type : "POST",
      contentType: "application/json;charset=UTF-8",
      url : urls.searchUrl,
      data : JSON.stringify({name}),
      async: false,
      success : function(res) {
        let data = res.value
        result = {
          nodes:data.nodes.map( item => {
            return {
              ...item,
              label:item.name,
              properties:{
                ...item
              }
            }
          }),
          links:data.links.map( item => {
            return {
              ...item,
              label:item.relation,
              lineWidth:3
            }
          })
        }
      },
      error : function(e){
        console.log(e);
      }
    });
    return result
  }
  function spreadNode(id) {
    let result;
    $.ajax({
      type : "POST",
      contentType: "application/json;charset=UTF-8",
      url : urls.fetchChildNodeUrl,
      data : JSON.stringify({id}),
      async: false,
      success : function(res) {
        let data = res.value
        result = {
          nodes:data.nodes.map( item => {
            return {
              ...item,
              label:item.name,
              properties:{
                ...item
              }
            }
          }),
          links:data.links.map( item => {
            return {
              ...item,
              label:item.relation,
              lineWidth:3
            }
          })
        }
      },
      error : function(e){
        console.log(e);
      }
    });
    return result
  }
  //  获取详细信息的方法
  function getDetail(node){
    this.getFieldLabel(node.id)
    const nodeMap = fieldMap
    let data = {...node}
    items = []
    nodeValue = {}
    Object.keys(nodeMap).forEach( label => {
      let key = nodeMap[label]
      items.push({
        header: label,
        field:key,
        rule:{},
        type:'text',
        value:data[key],
        readonly: true
      })
      nodeValue[key] = data[key]
    })
    if(data.uid){
      items = []
      nodeValue = {}
      getDetailData(data.uid,data.tableName)
    }
    if(data.type == 126){
      items.push({
        header: '试验次数',
        field: 'testNum',
        rule:{},
        type:'text',
        value:4,
        readonly: true
      })
      nodeValue['testNum'] = 4
    }
    if(data.url){
      getTxtData(data.url)
    }
  }
  //  获取详细信息数据的接口
  function getDetailData(uid,tableName){
    let param = JSON.stringify({
      filter:{
        id:[uid]
      }
    })
    $.ajax({
      type:'post',
      contentType: "application/json;charset=UTF-8",
      url: urls.getDetailUrl+tableName,
      data:param,
      async:false,
      success: function(res){
        let data = res.value.data[0],tempValue={}
        Object.keys(data).forEach( key => {
          if(key != 'id' && key != 'type' && key != 'uid'){
            nodeValue[key] = data[key]
          }
        })
        nodeValue = {
          ...nodeValue,
          tempValue
        }
      }
    })
    $.ajax({
      type:'get',
      url: urls.getHeaderUrl + tableName + '/headerWithOption',
      data: {},
      async:false,
      success: function(res){
        let data = res.value.cols,tempArr = []
        data.forEach( item => {
          item.readonly = true
          item.value = nodeValue[item.field]
          if(item.field == 'id' || !nodeValue[item.field]){
            item.hidden = true
          }
          tempArr.push(item)
        })
        items.push(...tempArr)
      }
    })
  }
  // 获取详细信息的url数据
  function getTxtData(filePath){
    $.ajax({
      type:'post',
      url: urls.readTxtUrl,
      data:{
        filePath:filePath
      },
      async:false,
      success: function(res){
        let data = res.value
        items.push({
          header:'文本内容',
          field:'txtContent',
          value:data,
          hidden: false
        })
      }
    })
  }
  // 获取潜艇的事件
  function getEventData(node,pageNum,pageSize){
    let result = []
    $.ajax({
      type:'get',
      url: urls.eventUrl+`${pageNum}/${pageSize}`,
      dataType: 'json',
      data : {
      sign:node.uid,
      pageNum,pageSize},
      async:false,
      success: function(res){
        let data = res.value
        result = {
          data:data.data.map((item,index)=>{
            return {
              No:(pageNum-1)*pageSize+index+1,
              ...item
            }
          }),
          total: data.total
        }
      }
    })
    return result
  }
  // 获取对应的字段名
  function getFieldLabel(id){
    $.ajax({
      type:'post',
      contentType: "application/json;charset=UTF-8",
      url: urls.getFieldZN,
      data:JSON.stringify({id}),
      async: false,
      success: function(res){
        let data = res.value
        fieldMap = data
      }
    })
  }
  // delete删除接口
  function delNodes(id){
    $.ajax({
      type:'post',
      contentType: "application/json;charset=UTF-8",
      url: urls.delNodeUrl,
      data:JSON.stringify({id}),
      success: function(res) {
        if(res.value){
          console.log('删除成功');
        }
      }
    })
  }
  //  修改的数据
  function beforeUpdateNode(node) {
    let updateValue={}
    updateItems = []
    updateValue = {}
    getFieldLabel(node.id)
    let data = fieldMap
    for( let key in fieldMap){
      let header = key,field = data[key]
      updateItems.push({
        header,
        field,
        type:'text',
        value:node.properties[field],
        rule:[
          {
            required: true, message:'请输入'+key, trigger: 'blur'
          }
        ]
      })
    }
  }
  //  修改接口
  function postUpdateNode(node,data){
    let result = false
    $.ajax({
      type: 'post',
      contentType: "application/json;charset=UTF-8",
      url: urls.updateNodeUrl,
      async: false,
      data:JSON.stringify({
        id:node.id,
        type:node.type,
        ...data
      }),
      success: function(res) {
        //  是否修改成功的提示
        result = res.value
      }
    })
    return result
  }
  //  新增节点
  function postAddNode(node,data){
    let result = ''
    $.ajax({
      type:'post',
      url: urls.addNodeUrl,
      contentType: "application/json;charset=UTF-8",
      async:false,
      data:JSON.stringify({
        type: node.type,
        oldId: node.id,
        ...data
      }),
      success: function(res) {
        let data = res.value
        result = data
      }
    })
    return result
  }
  //  新增节点之间的关系
  function addRelation(startId,endId,relation){
    // 添加二者之间的关系
    let result = false
    $.ajax({
      type:'post',
      url:urls.addRelationUrl,
      contentType: "application/json;charset=UTF-8",
      data:JSON.stringify({
        startId,
        endId,
        relation
      }),
      async:false,
      success: function(res) {
        //  新增节点的信息，设计到新增节点以及新增关系
        //  需要获取关系的类型，以及新增节点的类型
        result = res.value.id
      }
    })
    return result
  }
  //  修改节点之间的关系
  function updateRelation(startId,endId,relationId,relation){
    // updateRelationUrl
    let result = false
    $.ajax({
      type:'post',
      url:urls.updateRelationUrl,
      contentType: "application/json;charset=UTF-8",
      data:JSON.stringify({
        startId,
        endId,
        relationId,
        relation
      }),
      async:false,
      success: function(res) {
        result = res.value
      }
    })
    return result
  }
  // 删除节点之间的关系
  function delRelation(id){
    let result = false
    $.ajax({
      type:'post',
      url:urls.delRelationUrl,
      contentType: "application/json;charset=UTF-8",
      data:JSON.stringify({
        relationId:id
      }),
      async:false,
      success: function(res) {
        result = res.value
      }
    })
    return result
  }
  //  获取质量系数
  function getQualityRate(url){
    let result
    $.ajax({
      type:'post',
      url:urls.qualityUrl,
      data:{
        url
      },
      async:false,
      success: function(res){
        let data = res.value
        result = data
      }
    })
    return result
  }
  //  依据爷孙关系获取新数据
  function getYeSuRelation(param){
    let result = {}
    $.ajax({
      url: urls.relationReasoning,
      type: 'post',
      data:JSON.stringify({
        ...param
      }),
      contentType: "application/json;charset=UTF-8",
      async: false,
      success: function(res){
        let data = res.value
        result = {
          nodes:data.nodes.map( d=>{
            return {
              ...d,
              label:d.name,
              properties:d
            }
          }),
          links:data.links.map( d=> {
            return {
              ...d,
              label:d.relation,
              lineWidth:1
            }
          })
        }
      }
    })
    return result
  }
  //  获取图片数据
  function getImageData(){
    $.ajax({
      type:'get',
      url: urls.typeUrl,
      data:{},
      success: function(res){
        let data = res.value
        for(let key in data){
          if(staticNodeMap[key]){
            if(typeof staticNodeMap[key] == 'object'){
              staticNodeMap[key].forEach( d => {
                nodesLegend.push(nodeList[d])
              })
            }else{
              nodesLegend.push(nodeList[staticNodeMap[key]])
            }

          }else{
            nodesLegend.push({
              type: +key,
              field: "type",
              color: colorList[index++]
            })
          }
          typeMap[key] = data[key]
        }
      }
    })
  }
  function getImage(node){
    for(let i=0;i<nodesLegend.length;i++){
      if(node.name == nodesLegend[i].type){
        // node.image = `images/${node.name}.png`
        node.color = `rgb(${nodesLegend[i].color})`
        break;
      }else if(node.type == nodesLegend[i].type){
        node.color = `rgb(${nodesLegend[i].color})`
        break;
      }
    }
  }
  //  获取该节点下的关系
  function getRelation(){
    relationList = []
    $.ajax({
      type:'post',
      url: urls.getRelationUrl,
      contentType: "application/json;charset=UTF-8",
      data: JSON.stringify({
        id:parentNode.id
      }),
      async:false,
      success: function(res){
        let data = res.value
        if(!data.length){
          canAddNode = false
          return
        }else{
          canAddNode = true
        }
        addItems[0]['option'] = data.map(d=>({label:d,value:d}))
      }
    })
  }
  // 获取子节点类型
  function getChildType(relation){
    nodeTypeList = []
    $.ajax({
      type:'post',
      contentType: "application/json;charset=UTF-8",
      url: urls.getChildUrl,
      async:false,
      data:JSON.stringify({
        name:parentNode.name,
        relation
      }),
      success: function( res ){
        let data = res.value
        addItems[1]['option'] = data.map(d=>({label:d,value:d}))
        // _this.nodeTypeList = data
      }
    })
  }
  function getField(label){
    // this.isFirst = false
    $.ajax({
      type:'post',
      url: urls.getFieldUrl,
      contentType: "application/json;charset=UTF-8",
      data:JSON.stringify({label}),
      async:false,
      success:function(res){
        let data = res.value
        let keys = Object.keys(data)
        if(!keys.length) return
        keys.forEach( key => {
          addItems.push({
            header:key,
            field:data[key],
            type:'text',
            value:'',
            rule:[
              {
                required: true, message:`请输入${key}`, trigger: 'blur'
              }
            ]
          })
        })
      }
    })
  }
  function changeSelect(item,value){
    if(item == 'relation'){
      value && getChildType(value)
    }
    else if(item == 'label'){
      // value && this.isFirst && this.getField(value)
      value && getField(value)
    }
  }
  function addChildNode(node) {
    parentNode = { ...node}
    addItems = [
       {
        field:'relation',
        header:'关系',
        type:'select',
        option:[],
        rule:[
          {
            required: true, message:'请选择关系', trigger: 'change'
          }
        ]
      },
      {
        field:'label',
        header:'类型',
        type:'select',
        option:[],
        rule:[
          {
            required: true, message:'请选择类型', trigger: 'change'
          }
        ]
      }
    ]
    addValue = {
      relation:'',
      label:'',
    }
    getRelation()
    return canAddNode
  }
  // 根据潜艇型号查看国家
  function getSubmarineCountry(node){
    let country = ''
    $.ajax({
      type:'post',
      url: urls.getSubmarineCountryUrl,
      contentType: "application/json;charset=UTF-8",
      data:JSON.stringify({model:node.name}),
      async:false,
      success: function(res){
        country = res.value
      }
    })
    return country
  }
  //  获取节点树
  function getNodeTree(){
    let nodeTree = []
    return new Promise(function(resolve,reject){
      $.ajax({
        type:'get',
        url:urls.getNodeTreeInitUrl,
        contentType: "application/json;charset=UTF-8",
        data:{},
        async:false,
        success: function(res){
          if(res.value){
            nodeTree = res.value.map(d=>{
              d.title = d.name
              return d
            })
          }
          console.log(nodeTree);
          resolve(nodeTree)
        }
      })
    })
    console.log(nodeTree);
    return nodeTree
  }
